<template>
  <div class="database-manage-container">
    <div class="page-header">
      <h2 class="page-title">数据库管理</h2>
      <a-button type="primary" @click="showAddDatabaseModal">
        <plus-outlined /> 添加数据源
      </a-button>
    </div>

    <div class="database-list">
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" v-for="db in databaseList" :key="db.id">
          <a-card class="database-card" hoverable>
            <div class="database-logo">
              <img :src="getDbIcon(db.type)" :alt="db.name" />
            </div>
            <div class="database-name">{{ db.name }}</div>
            <div class="database-description">{{ db.description }}</div>
            <div class="database-actions">
              <a-space>
                <a-button type="link" size="small" @click="editDatabase(db)">编辑</a-button>
                <a-popconfirm
                  title="确定要删除此数据源吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteDatabase(db.id)"
                >
                  <a-button type="link" danger size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 添加/编辑数据库对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑数据源' : '添加数据源'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" layout="vertical">
        <a-form-item label="数据源名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入数据源名称" />
        </a-form-item>
        
        <a-form-item label="数据源类型" name="type">
          <database-provider-selector v-model="formState.type" @select="handleTypeSelect" />
        </a-form-item>
        
        <a-form-item label="连接地址" name="host">
          <a-input v-model:value="formState.host" placeholder="请输入连接地址" />
        </a-form-item>
        
        <a-form-item label="端口" name="port">
          <a-input-number v-model:value="formState.port" style="width: 100%" placeholder="请输入端口" />
        </a-form-item>
        
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        
        <a-form-item label="数据库名" name="database">
          <a-input v-model:value="formState.database" placeholder="请输入数据库名" />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formState.description" :rows="3" placeholder="请输入描述信息" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import type { DatabaseItem } from '../types/database';
import DatabaseProviderSelector, { getDefaultPort } from '../components/DatabaseProviderSelector.vue';

// 引入所有数据库图标
import mysqlIcon from '../assets/icons/database/mysql.png';
import postgresqlIcon from '../assets/icons/database/postgresql.png';
import sqlserverIcon from '../assets/icons/database/sqlserver.png';
import oracleIcon from '../assets/icons/database/oracle.png';
import sqliteIcon from '../assets/icons/database/sqlite.png';
import cassandraIcon from '../assets/icons/database/cassandra.png';
import clickhouseIcon from '../assets/icons/database/clickhouse.png';
import couchbaseIcon from '../assets/icons/database/couchbase.png';
import db2Icon from '../assets/icons/database/db2.png';
import dorisIcon from '../assets/icons/database/doris.png';
import firebirdIcon from '../assets/icons/database/firebird.png';
import hanaIcon from '../assets/icons/database/hana.png';
import hiveIcon from '../assets/icons/database/hive.png';
import kylinIcon from '../assets/icons/database/kylin.png';
import mariadbIcon from '../assets/icons/database/mariadb.png';
import oceanbaseIcon from '../assets/icons/database/oceanbase.png';
import prestodbIcon from '../assets/icons/database/prestodb.png';
import snowflakeIcon from '../assets/icons/database/snowflake.png';
import teradataIcon from '../assets/icons/database/teradata.png';
import tidbIcon from '../assets/icons/database/tidb.png';
import verticaIcon from '../assets/icons/database/vertica.png';
import accessIcon from '../assets/icons/database/access.png';
import kingbaseIcon from '../assets/icons/database/kingbase.png';
import damengIcon from '../assets/icons/database/dameng.png';
import gaussdbIcon from '../assets/icons/database/gaussdb.png';

// 图标映射
const dbIcons: Record<string, any> = {
  mysql: mysqlIcon,
  postgresql: postgresqlIcon,
  sqlserver: sqlserverIcon,
  oracle: oracleIcon,
  sqlite: sqliteIcon,
  cassandra: cassandraIcon,
  clickhouse: clickhouseIcon,
  couchbase: couchbaseIcon,
  db2: db2Icon,
  doris: dorisIcon,
  firebird: firebirdIcon,
  hana: hanaIcon,
  hive: hiveIcon,
  kylin: kylinIcon,
  mariadb: mariadbIcon,
  oceanbase: oceanbaseIcon,
  prestodb: prestodbIcon,
  snowflake: snowflakeIcon,
  teradata: teradataIcon,
  tidb: tidbIcon,
  vertica: verticaIcon,
  access: accessIcon,
  kingbase: kingbaseIcon,
  dameng: damengIcon,
  gaussdb: gaussdbIcon
};

// 获取数据库图标
const getDbIcon = (type: string) => {
  return dbIcons[type] || '';
};

// 数据库列表
const databaseList = ref<DatabaseItem[]>([]);

// 表单相关
const formRef = ref();
const modalVisible = ref(false);
const isEdit = ref(false);
const currentDatabase = ref<DatabaseItem | null>(null);

// 表单状态
const formState = reactive({
  name: '',
  type: 'mysql',
  host: '',
  port: 3306,
  username: '',
  password: '',
  database: '',
  description: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入数据源名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据源类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入连接地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

// 处理数据库类型选择，自动设置默认端口
const handleTypeSelect = (provider: any) => {
  formState.port = getDefaultPort(provider.id);
};

// Mock数据 - 生成数据库列表
const generateMockDatabaseList = () => {
  return [
    {
      id: '1',
      name: 'MySQL生产环境',
      type: 'mysql',
      host: 'mysql.example.com',
      port: 3306,
      username: 'admin',
      password: '********',
      database: 'production_db',
      description: '生产环境主数据库，存储核心业务数据',
      logo: mysqlIcon,
      createdAt: '2023-09-01',
      updatedAt: '2023-09-01'
    },
    {
      id: '2',
      name: 'PostgreSQL分析库',
      type: 'postgresql',
      host: 'postgres.example.com',
      port: 5432,
      username: 'analyst',
      password: '********',
      database: 'analytics_db',
      description: '数据分析专用数据库，存储分析结果和报表数据',
      logo: postgresqlIcon,
      createdAt: '2023-09-05',
      updatedAt: '2023-09-05'
    },
    {
      id: '3',
      name: 'Oracle财务库',
      type: 'oracle',
      host: 'oracle.example.com',
      port: 1521,
      username: 'finance',
      password: '********',
      database: 'finance_db',
      description: '财务系统数据库，存储财务和会计数据',
      logo: oracleIcon,
      createdAt: '2023-09-10',
      updatedAt: '2023-09-10'
    },
    {
      id: '4',
      name: 'SQL Server用户系统',
      type: 'sqlserver',
      host: 'sqlserver.example.com',
      port: 1433,
      username: 'userdb',
      password: '********',
      database: 'users_db',
      description: '用户管理系统数据库，存储用户信息和权限数据',
      logo: sqlserverIcon,
      createdAt: '2023-09-15',
      updatedAt: '2023-09-15'
    }
  ];
};

// 获取数据库列表 - Mock数据
const fetchDatabaseList = () => {
  // 模拟API请求延迟
  setTimeout(() => {
    databaseList.value = generateMockDatabaseList();
  }, 300);
};

// 显示添加数据源对话框
const showAddDatabaseModal = () => {
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 编辑数据源
const editDatabase = (db: DatabaseItem) => {
  isEdit.value = true;
  currentDatabase.value = db;
  
  // 填充表单数据
  formState.name = db.name;
  formState.type = db.type;
  formState.host = db.host;
  formState.port = db.port;
  formState.username = db.username;
  formState.password = db.password;
  formState.database = db.database;
  formState.description = db.description || '';
  
  modalVisible.value = true;
};

// 删除数据源
const deleteDatabase = (id: string) => {
  // 模拟删除操作
  databaseList.value = databaseList.value.filter(item => item.id !== id);
  message.success('数据源删除成功');
};

// 处理模态框确认
const handleModalOk = () => {
  formRef.value.validate().then(() => {
    if (isEdit.value && currentDatabase.value) {
      // 模拟更新数据源
      const index = databaseList.value.findIndex(item => item.id === currentDatabase.value?.id);
      if (index !== -1) {
        databaseList.value[index] = {
          ...databaseList.value[index],
          name: formState.name,
          type: formState.type,
          host: formState.host,
          port: formState.port,
          username: formState.username,
          password: formState.password,
          database: formState.database,
          description: formState.description,
          updatedAt: new Date().toISOString().split('T')[0]
        };
        message.success('数据源更新成功');
      }
    } else {
      // 模拟添加数据源
      const newDatabase: DatabaseItem = {
        id: Math.random().toString(36).substring(2, 11),
        name: formState.name,
        type: formState.type,
        host: formState.host,
        port: formState.port,
        username: formState.username,
        password: formState.password,
        database: formState.database,
        description: formState.description,
        logo: getDbIcon(formState.type),
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0]
      };
      
      databaseList.value.unshift(newDatabase);
      message.success('数据源添加成功');
    }
    
    modalVisible.value = false;
    resetForm();
  }).catch((error: any) => {
    console.log('表单验证失败', error);
  });
};

// 取消模态框
const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 重置一些表单外的字段
  formState.type = 'mysql';
  formState.port = getDefaultPort('mysql');
  formState.description = '';
};

onMounted(() => {
  fetchDatabaseList();
});
</script>

<style scoped>
.database-manage-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.database-list {
  margin-top: 16px;
}

.database-card {
  height: 100%;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px 16px;
}

.database-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.database-logo img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.database-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.database-description {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  min-height: 60px;
  margin-bottom: 16px;
}

.database-actions {
  margin-top: auto;
}
</style> 